<template>
  <div class="ai-tools-container">
    <ai-tools-top>
      <div slot="top-left"
        class="flex items-center gap-2">
        <svg-icon className="w-4 h-4"
          iconName='setting'></svg-icon>
        <h1 class="text-base text-white font-bold">
          {{$t('aitools_aiTools')}}
        </h1>
      </div>
      <div slot="top-right"
        class="flex items-center w-full pb-2.5 mb-2.5 border-b border-white border-opacity-30 md:border-t-0 md:pb-0 md:mb-0 md:w-auto md:border-b-0">
        <span class="text-sm text-white">
          {{$t('aitools_total100Articles', {num: total})}}
        </span>
        <div class="md:w-px md:h-5 bg-white bg-opacity-30 md:mx-5"></div>
      </div>
    </ai-tools-top>

    <div class="bg-gray-1100 py-5 px-4">
      <div class="max-w-15xl mx-auto text-lg text-gray-2700">
        {{$t('aitools_warn')}}
      </div>
    </div>
    <template v-if="hasRealVal(articlesListFirst) && articlesListFirst.length > 0">
      <div class="pt-7 pb-3 lg:pb-7 px-4">
        <div class="max-w-15xl mx-auto grid gap-y-6 gap-x-14 sm:grid-cols-6">
          <div class="article-item col-span-6 sm:col-span-2 lg:col-span-3 lg:row-span-5"
            v-if="hasRealVal(articlesListFirst) && articlesListFirst.length > 0">
            <common-link path="/top-ai-tools/:handle"
              :params="{ handle:articlesListFirst[0].handle }"
              class="block mb-3 lg:mb-4 aspect-pic-left">
              <common-image class="w-full h-auto"
                :src="articlesListFirst[0].image ? $vResetPic(articlesListFirst[0].image, 600) : 'https://cdn.toolify.ai/default.webp'"
                :alt="articlesListFirst[0].name"></common-image>
            </common-link>
            <common-link path="/top-ai-tools/:handle"
              :params="{ handle:articlesListFirst[0].handle }"
              class="block mb-3 lg:mb-4 group">
              <h5 class="text-lg lg:text-2xl text-gray-2700 font-bold group-hover:text-purple-1300 break-words line-2">
                {{articlesListFirst[0].title}}
              </h5>
            </common-link>
            <p class="text-sm text-gray-2800 mb-2 lg:mb-2.5 break-words"
              v-if="hasRealVal(articlesListFirst[0].author)"
              v-html="$t('aitools_byAuthorOnDate',{author: authorOptions[parseInt(articlesListFirst[0].author)].author,date: $formattedDate(articlesListFirst[0].published_at, fI18n, locale)})">
            </p>
            <p class="text-sm lg:text-lg text-gray-2700 break-words line-2"
              v-if="hasRealVal(articlesListFirst[0].page_description)">
              {{articlesListFirst[0].page_description}}
            </p>
          </div>
          <template v-if="hasRealVal(articlesListSecond) && articlesListSecond.length > 0">
            <div class="article-item col-span-6 sm:col-span-2 lg:col-span-3 lg:grid lg:gap-4 lg:grid-cols-6"
              v-for="(item, key) in articlesListSecond">
              <common-link path="/top-ai-tools/:handle"
                :params="{ handle:item.handle }"
                class="block mb-3 lg:mb-0 sm:col-span-2 aspect-pic-right">
                <common-image class="w-full h-auto"
                  :src="item.image ? $vResetPic(item.image,600) : 'https://cdn.toolify.ai/default.webp'"
                  :alt="item.name"></common-image>
              </common-link>
              <div class="sm:col-span-4">
                <common-link path="/top-ai-tools/:handle"
                  :params="{ handle:item.handle }"
                  class="block mb-3 group">
                  <h5 class="text-lg lg:text-28 lg:text-lg text-gray-2700 font-bold group-hover:text-purple-1300 break-words line-2">
                    {{item.title}}
                  </h5>
                </common-link>
                <p class="text-sm text-gray-2800 mb-2 lg:mb-0 break-words"
                  v-if="hasRealVal(item.author)"
                  v-html="$t('aitools_byAuthorOnDate',{author: authorOptions[parseInt(item.author)].author,date: $formattedDate(item.published_at, fI18n, locale)})">
                </p>
              </div>
              <p class="text-sm lg:text-lg text-gray-2700 block lg:hidden break-words line-2"
                v-if="hasRealVal(item.page_description)">
                {{item.page_description}}
              </p>
            </div>
          </template>
        </div>
      </div>

      <template v-if="hasRealVal(articlesListThird) && articlesListThird.length > 0">
        <div class="pt-3 pb-10 lg:pt-10 lg:pb-20 px-4">
          <div class="max-w-15xl mx-auto grid gap-y-6 gap-x-14 sm:grid-cols-3 lg:grid-cols-3 lg:gap-x-15 lg:gap-y-24">
            <div class="col-span-1"
              v-for="(item, key) in articlesListThird">
              <common-link path="/top-ai-tools/:handle"
                :params="{ handle:item.handle }"
                class="block mb-3 aspect-pic">
                <common-image class="w-full h-auto"
                  :src="item.image ? $vResetPic(item.image,600) : 'https://cdn.toolify.ai/default.webp'"
                  :alt="item.name"></common-image>
              </common-link>
              <common-link path="/top-ai-tools/:handle"
                :params="{ handle:item.handle }"
                class="block mb-3 group">
                <h5 class="text-lg text-gray-2700 font-bold group-hover:text-purple-1300 break-words line-2">{{item.title}}</h5>
              </common-link>
              <p class="text-sm text-gray-2800 mb-2 break-words"
                v-if="hasRealVal(item.author)"
                v-html="$t('aitools_byAuthorOnDate',{author: authorOptions[parseInt(item.author)].author,date: $formattedDate(item.published_at, fI18n, locale)})">
              </p>
              <p class="text-sm text-gray-2700 break-words line-2"
                v-if="hasRealVal(item.page_description)">
                {{item.page_description}}
              </p>
            </div>
          </div>
        </div>
      </template>
    </template>
    <el-empty v-else
      :description="$t('noResult')"></el-empty>

    <div class="mb-12 px-4"
      v-if="last_page>1">
      <div class="max-w-15xl mx-auto flex items-center gap-2.5">
        <common-link :path="page-1 === 1 ? '/top-ai-tools' : '/top-ai-tools/page/:page'"
          v-if="page>1"
          :params="page-1 === 1 ? {} : { page: page-1 }"
          class="flex items-center justify-center h-12 w-12 p1 border border-gray-3000 bg-gray-1100 text-black font-bold hover:border-purple-1300 hover:bg-purple-1300 hover:text-white">
          <svg-icon className="text-sm"
            iconName='arrow_left'></svg-icon>
        </common-link>
        <template v-for="(item,key) in pageList">
          <common-link :path="item === 1 ? '/top-ai-tools' : '/top-ai-tools/page/:page'"
            :key="key"
            :params="item === 1 ? {} : { page: item }"
            v-if="item!==page"
            class="flex items-center justify-center h-12 w-12 p1 border border-gray-3000 bg-gray-1100 text-sm text-black font-bold hover:border-purple-1300 hover:bg-purple-1300 hover:text-white">
            {{item}}
          </common-link>
          <span class="flex items-center justify-center h-12 w-12 p1 border  text-sm font-bold border-purple-1300 bg-purple-1300 text-white"
            v-else>
            {{item}}
          </span>
        </template>
        <common-link path="/top-ai-tools/page/:page"
          v-if="hasRealVal(next_page_url)"
          :params="{ page: page+1 }"
          class="flex items-center justify-center h-12 w-12 p1 border border-gray-3000 bg-gray-1100 text-black font-bold hover:border-purple-1300 hover:bg-purple-1300 hover:text-white">
          <svg-icon className="text-sm"
            iconName='arrow_right_purple2'></svg-icon>
        </common-link>
      </div>
    </div>

    <the-best-ai-websites></the-best-ai-websites>
  </div>
</template>

<script>
import authorOptions from '@/assets/json/authorOptions.json'
import { mapState } from 'vuex'
export default {
  name: 'AiTools',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
      script: [
        {
          json: {
            '@context': 'https://schema.org',
            '@type': 'Article',
            name: this.title,
            headline: this.description,
            image: ['https://cdn.toolify.ai/default.webp'],
            author: {
              '@type': 'Organization',
              name: 'toolify',
              url: 'https://www.toolify.ai',
            },
            description: this.description,
            articleSection: 'Technology',
            mainEntityOfPage: `https://www.toolify.ai${this.$route.fullPath}`,
            publisher: {
              '@context': 'https://www.toolify.ai',
              '@type': 'Organization',
              name: 'Toolify',
              legalName: 'Toolify Inc',
              url: 'https://www.toolify.ai',
              logo: 'https://www.toolify.ai/favicon.ico',
              foundingDate: '2023',
              founders: [
                {
                  '@type': 'Organization',
                  name: 'toolify',
                },
              ],
              address: {
                '@type': 'PostalAddress',
                streetAddress: '1942 Broadway St STE 314C Boulder',
                addressLocality: 'Colorado',
                addressRegion: 'CO',
                postalCode: '80302',
                addressCountry: 'US',
              },
              contactPoint: {
                '@type': 'ContactPoint',
                contactType: 'customer support',
                email: 'business@toolify.ai',
              },
              sameAs: ['https://twitter.com/samChan3890089'],
            },
            name: this.title,
            breadcrumb: {
              '@type': 'BreadCrumbList',
              itemListElement: [
                {
                  '@type': 'ListItem',
                  position: 1,
                  name: this.$t('home'),
                  item: `https://www.toolify.ai${
                    this.locale === 'en' ? '' : `/${this.locale}`
                  }`,
                },
                {
                  '@type': 'ListItem',
                  position: 2,
                  name: this.$t('aitools_topAITools'),
                },
              ],
            },
          },
          type: 'application/ld+json',
        },
      ],
    }
  },
  async asyncData({ app, route, params, $axiosApi, error }) {
    try {
      let [articleRes] = await Promise.all([
        await $axiosApi.getTopArticles({
          page: params.page ? params.page : 1,
          per_page: 24,
        }),
      ])

      let res = {}
      if (articleRes.code === 200) {
        if (articleRes.data.data.length > 0) {
          res.articlesListFirst = articleRes.data.data.slice(0, 1)
        }
        if (articleRes.data.data.length > 1) {
          res.articlesListSecond = articleRes.data.data.slice(1, 6)
        }
        if (articleRes.data.data.length > 7) {
          res.articlesListThird = articleRes.data.data.slice(6)
        }

        res.total = articleRes.data.total
        res.page = articleRes.data.current_page
          ? articleRes.data.current_page
          : 1
        res.next_page_url = articleRes.data.next_page_url
          ? articleRes.data.next_page_url
          : null
        res.last_page = articleRes.data.last_page
          ? articleRes.data.last_page
          : null

        function generatePageNumbers(currentPage, maxPage, adjacentCount) {
          let startPage = Math.max(currentPage - adjacentCount, 1)
          let endPage = Math.min(currentPage + adjacentCount, maxPage)

          const extraPagesNeededStart = Math.max(
            adjacentCount - (currentPage - startPage),
            0
          )
          const extraPagesNeededEnd = Math.max(
            adjacentCount - (endPage - currentPage),
            0
          )

          startPage = Math.max(
            startPage - extraPagesNeededEnd - extraPagesNeededStart,
            1
          )
          endPage = Math.min(
            endPage + extraPagesNeededStart + extraPagesNeededEnd,
            maxPage
          )

          return Array.from(
            { length: endPage - startPage + 1 },
            (_, i) => startPage + i
          )
        }

        res.pageList = generatePageNumbers(res.page, res.last_page, 4)
      } else {
        if (articleRes && articleRes.code && articleRes.code === 404) {
          error({ statusCode: 404 })
        } else if (
          !(articleRes && articleRes.code && articleRes.code === 401)
        ) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: articleRes.code,
          })
        }
      }

      let description = app.i18n.t('aitools_pageDesc')
      let title = app.i18n.t('aitools_pageTitle')

      return {
        ...res,
        title,
        description,
      }
    } catch (err) {
      console.log(err)
    }
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  data() {
    return {
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,
      title: null,
      description: null,

      articlesListFirst: [],
      articlesListSecond: [],
      articlesListThird: [],
      pageList: [],
      page: 1,
      per_page: 24,
      next_page_url: null,
      last_page: null,
      loading: false,
      total: 0,

      authorOptions: authorOptions,
    }
  },
  methods: {
    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },
  },
}
</script>
<style lang='scss' scoped>
.ai-tools-container {
  font-family: toolify-primary;
  .aspect-pic-left,
  .aspect-pic-right,
  .aspect-pic {
    aspect-ratio: 265 / 139;
  }
}
@media (min-width: 1024px) {
  .ai-tools-container {
    .aspect-pic-left {
      aspect-ratio: 265 / 139;
    }
    .aspect-pic-right {
      aspect-ratio: 80 / 41;
    }
    .aspect-pic {
      aspect-ratio: 333 / 175;
    }
  }
}
</style>
